package com.itheima.app.service.impl;

import com.aliyun.tea.TeaException;
import com.itheima.app.mapper.UserMapper;
import com.itheima.app.service.RedisService;
import com.itheima.app.service.UserService;
import com.itheima.app.utils.SendNoteUtil;

import com.itheima.health.model.pojos.PhoneNumber;
import com.itheima.health.model.pojos.User;

import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;


@Service
//@Api(tags = "用户相关")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SendNoteUtil sendNoteUtil;
    @Value("${redis.key.prefix.validateCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    //过期时间60秒
    @Value("${redis.key.expire.validateCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

  // @ApiOperation(value = "发送验证码")
    @Override
    public void sendCaptcha(String phone){
        String template = "SMS_460761293";
        sendNoteUtil.sendNoteMessgae(phone,template);
    }


    @Override
    //快速登录
    public String quickLogin(PhoneNumber phoneNumber) {
        User user = new User();
        if (userMapper.getPhoneNumbers(phoneNumber.getTelephone()) != null) {
            if (!verifyAuthCode(phoneNumber.getTelephone(), phoneNumber.getValidateCode())) {
                return "验证码错误";
            } else return "登陆成功";
        } else {
            user.setTelephone(phoneNumber.getTelephone());
            userMapper.insertUser(user);
        }
        return null;
    }

//@ApiOperation(value = "用户验证码格式验证")
public static boolean isValidPhoneNumber(String phoneNumber) {
    if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
        return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
    }
    return false;
}
    //对输入的验证码进行校验
    private boolean verifyAuthCode(String validateCode, String telephone){
        if(StringUtils.isEmpty(validateCode)){
            return false;
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        return validateCode.equals(realAuthCode);
    }
}
